package com.py.credit.controller;

import com.py.credit.common.Page;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.*;
import com.py.credit.service.DeptDataService;
import com.py.credit.service.LhjcRemoteBaseService;
import com.py.credit.service.OfficeService;
import com.py.framework.core.helper.HttpServletHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/deptData")
public class DeptDataController {

    @Autowired
    private DeptDataService deptDataService;

    @Autowired
    private LhjcRemoteBaseService lhjcRemoteBaseService;

    @Autowired
    private OfficeService officeService;

    /**
     * 部门发起列表数据
     *
     * @param page      分页条件
     * @param startTime 起始时间
     * @param endTime   结束时间
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list.json")
    public RestServiceResult getList(Page page,
                                     @RequestParam(value = "startTime", defaultValue = "", required = true) String startTime,
                                     @RequestParam(value = "endTime", defaultValue = "", required = true) String endTime, HttpServletRequest request) {
        RestServiceResult<SysUser> user = lhjcRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null != userInfo) {

            } else {
                ExceptionLogger.error("DeptDataController#getList", "未获取到当前用户信息！");
                return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("DeptDataController#getList", "未获取到当前用户信息！");
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
        }

        List<DeptData> deptData = deptDataService.getListForPage(officeService.selectTopDeptId(userInfo.getOfficeId() + ""), startTime, endTime, page);
        List<Map<String, Object>> lhbms = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < deptData.size(); i++) {
            Set<String> set = new HashSet<String>();
            int gzid = deptData.get(i).getGzId();
            lhbms = deptDataService.selectForLhbm(gzid);
            String lhbm = "";
            for (Map<String, Object> map : lhbms) {
                set.add((String) map.get("deptName"));
            }
            for (String obj : set) {
                lhbm += obj + ",";
            }
            deptData.get(i).setLhbm(lhbm.substring(0, lhbm.length() - 1));
        }

        return new RestServiceResult(page.getTotalCount(), deptData);
    }

    /**
     * 查看详情
     *
     * @param ajbh 事件编号
     * @return
     */
    @ResponseBody
    @RequestMapping("/selectOneByAjbh.json")
    public RestServiceResult selectOneByAjbh(@RequestParam(defaultValue = "", required = true, value = "ajbh") String ajbh) {
        DeptData deptData = deptDataService.selectByAjbh(ajbh);
        int gzId = deptData.getGzId();
        String tybm = deptData.getTybm();
        String type = deptData.getType();
        Companymess companymess = deptDataService.selectByTybm(tybm, type);
        List<Measure> measures = deptDataService.selectCsByAjbh(gzId);
        Map<String, Object> map = new HashMap<String, Object>();
        List<String> list = new ArrayList<String>();
        List<Person> list1 = new ArrayList<Person>();
        if (deptData.getIs_associated().equals("Y")) {
            String[] zrrAjbh = deptData.getGlcf().split(",");
            for (int i = 0; i < zrrAjbh.length; i++) {
                DeptData deptData1 = deptDataService.selectByAjbh(zrrAjbh[i]);
                list.add(deptData1.getBm());
            }
            for (int i = 0; i < list.size(); i++) {
                Person person = deptDataService.selectZrrInfo(list.get(i));
                list1.add(person);
            }
        }

        map.put("deptData", deptData);
        map.put("companymess", companymess);
        map.put("measures", measures);
        map.put("person", list1);
        return new RestServiceResult(map);
    }

    /**
     * Excel统计导出
     *
     * @param response
     * @param startTime 起始时间
     * @param endTime   结束时间
     * @param type      F:部门发起 P:部门参与
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/exportExcel.json")
    public RestServiceResult excelExport(HttpServletResponse response,
                                         @RequestParam(value = "startTime", defaultValue = "", required = true) String startTime,
                                         @RequestParam(value = "endTime", defaultValue = "", required = true) String endTime,
                                         @RequestParam(value = "type", defaultValue = "", required = true) String type,
                                         HttpServletRequest request) throws IOException {
        RestServiceResult<SysUser> user = lhjcRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null != userInfo) {

            } else {
                ExceptionLogger.error("DeptDataController#excelExport", "未获取到当前用户信息！");
                return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("DeptDataController#excelExport", "未获取到当前用户信息！");
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
        }

        deptDataService.excelExport(response, startTime, endTime, officeService.selectTopDeptId(userInfo.getOfficeId() + ""), type);
        return new RestServiceResult(RestServiceResult.CODE_SUCCESS, "导出成功");
    }

    /**
     * 反馈详情
     *
     * @param ajbh   事件编号
     * @param deptId 部门id
     * @return
     */
    @RequestMapping("/feedbackDetail.json")
    public RestServiceResult feedbackDetail(@RequestParam(defaultValue = "", required = true, value = "ajbh") String ajbh,
                                            @RequestParam(defaultValue = "", required = true, value = "deptId") String deptId) {
        List<Feedback> feedbacks = deptDataService.getFeedbackDetail(ajbh, deptId);
        return new RestServiceResult(feedbacks);
    }

//-------------------------------------------------------------------以下为部门看板中获取图表数据的方法------------------------------------------------------------

    /**
     * 部门发起的惩戒和奖惩的数量
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/deptReportNum.json")
    public RestServiceResult deptReportNum(@RequestParam(defaultValue = "", required = true, value = "startTime") String startTime,
                                           @RequestParam(defaultValue = "", required = true, value = "endTime") String endTime, HttpServletRequest request) {
        RestServiceResult<SysUser> user = lhjcRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null != userInfo) {

            } else {
                ExceptionLogger.error("DeptDataController#deptReportNum", "未获取到当前用户信息！");
                return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("DeptDataController#deptReportNum", "未获取到当前用户信息！");
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
        }

        return new RestServiceResult(deptDataService.deptReportNum(officeService.selectTopDeptId(userInfo.getOfficeId() + ""), startTime, endTime));
    }

    /**
     * 事件状态
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param request
     * @return
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping("/eventStatus.json")
    public RestServiceResult eventStatus(@RequestParam(defaultValue = "", required = true, value = "startTime") String startTime,
                                         @RequestParam(defaultValue = "", required = true, value = "endTime") String endTime, HttpServletRequest request) throws ParseException {
        RestServiceResult<SysUser> user = lhjcRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null != userInfo) {

            } else {
                ExceptionLogger.error("DeptDataController#eventStatus", "未获取到当前用户信息！");
                return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("DeptDataController#eventStatus", "未获取到当前用户信息！");
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
        }

        Date dNow = new Date();   //当前时间
        Date dBefore = new Date();
        Calendar calendar = Calendar.getInstance(); //得到日历
        calendar.setTime(dNow);//把当前时间赋给日历
        calendar.add(calendar.MONTH, -11);  //设置为前12月
        dBefore = calendar.getTime();   //得到前12月的时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM"); //设置时间格式
        String defaultStartDate = sdf.format(dBefore);    //格式化前12月的时间
        String defaultEndDate = sdf.format(dNow); //格式化当前时间
        Map<String, Object> map = new HashMap<String, Object>();

        String deptId = officeService.selectTopDeptId(userInfo.getOfficeId() + "");

        //联合惩戒进行中的数量按月统计
        List<DeptNum> total = deptDataService.selectCjInfo(deptId, startTime, endTime);

        //联合惩戒移出的的数量按月统计
        List<DeptNum> tota2 = deptDataService.selectCjOutInfo(deptId, startTime, endTime);

        //联合激励进行中的数量按月统计
        List<DeptNum> tota3 = deptDataService.selectJlInfo(deptId, startTime, endTime);

        //联合激励移出的数量按月统计
        List<DeptNum> tota4 = deptDataService.selectJlOutInfo(deptId, startTime, endTime);

        map.put("total", total);
        map.put("tota2", tota2);
        map.put("tota3", tota3);
        map.put("tota4", tota4);
        if (startTime.equals("") || startTime == null) {
            startTime = defaultStartDate;
        } else {
            SimpleDateFormat sdfnew = new SimpleDateFormat("yyyy-MM-dd");
            startTime = sdf.format(sdfnew.parse(startTime));
        }

        if (endTime.equals("") || endTime == null) {
            endTime = defaultEndDate;
        } else {
            SimpleDateFormat sdfnew = new SimpleDateFormat("yyyy-MM-dd");
            endTime = sdf.format(sdfnew.parse(endTime));
            ;
        }
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        return new RestServiceResult(map);
    }

    /**
     * 部门发起中6个仪表盘数据
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param request
     * @return
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping("/sixDashboard.json")
    public RestServiceResult sixDashboard(@RequestParam(defaultValue = "", required = true, value = "startTime") String startTime,
                                          @RequestParam(defaultValue = "", required = true, value = "endTime") String endTime, HttpServletRequest request) throws ParseException {
        RestServiceResult<SysUser> user = lhjcRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null != userInfo) {

            } else {
                ExceptionLogger.error("DeptDataController#sixDashboard", "未获取到当前用户信息！");
                return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("DeptDataController#sixDashboard", "未获取到当前用户信息！");
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
        }

        Map<String, Object> map = new HashMap<String, Object>();

        String deptId = officeService.selectTopDeptId(userInfo.getOfficeId() + "");

        //本部门发起总量
        int total1 = deptDataService.selectDeptFq(deptId, startTime, endTime);

        //各部门响应事件数量
        int total2 = deptDataService.selectDeptXy(deptId, startTime, endTime);

        //联合奖惩事件涉及部门
        int total3 = deptDataService.selectDeptSj(deptId, startTime, endTime);

        //部门累计反馈次数
        int total4 = deptDataService.selectDeptLj(deptId, startTime, endTime);

        //涉及联合奖惩规则数量
        int total5 = deptDataService.selectSjGz(deptId, startTime, endTime);

        //关联处罚责任人数量
        List<String> list = deptDataService.selectCfZrr(deptId, startTime, endTime);
        List<String> list1 = new ArrayList<String>();
        for (int i = 0; i < list.size(); i++) {
            list1.add(list.get(i) + ",");
        }
        int total6 = list1.size();

        map.put("total1", total1);
        map.put("total2", total2);
        map.put("total3", total3);
        map.put("total4", total4);
        map.put("total5", total5);
        map.put("total6", total6);
        return new RestServiceResult(map);
    }

    /**
     * 部门实际参与的惩戒和奖惩的数量
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/deptPhReportNum.json")
    public RestServiceResult deptPhReportNum(@RequestParam(defaultValue = "", required = true, value = "startTime") String startTime,
                                             @RequestParam(defaultValue = "", required = true, value = "endTime") String endTime, HttpServletRequest request) {
        RestServiceResult<SysUser> user = lhjcRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null != userInfo) {

            } else {
                ExceptionLogger.error("DeptDataController#deptPhReportNum", "未获取到当前用户信息！");
                return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("DeptDataController#deptPhReportNum", "未获取到当前用户信息！");
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
        }

        return new RestServiceResult(deptDataService.deptPhReportNum(officeService.selectTopDeptId(userInfo.getOfficeId() + ""), startTime, endTime));
    }

    /**
     * 参与情况
     *
     * @param startTime 起始时间
     * @param endTime   结束时间
     * @param request
     * @return
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping("/partake.json")
    public RestServiceResult partake(@RequestParam(defaultValue = "", required = true, value = "startTime") String startTime,
                                     @RequestParam(defaultValue = "", required = true, value = "endTime") String endTime, HttpServletRequest request) throws ParseException {
        RestServiceResult<SysUser> user = lhjcRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null != userInfo) {

            } else {
                ExceptionLogger.error("DeptDataController#partake", "未获取到当前用户信息！");
                return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("DeptDataController#partake", "未获取到当前用户信息！");
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
        }

        Date dNow = new Date();   //当前时间
        Date dBefore = new Date();
        Calendar calendar = Calendar.getInstance(); //得到日历
        calendar.setTime(dNow);//把当前时间赋给日历
        calendar.add(calendar.MONTH, -11);  //设置为前12月
        dBefore = calendar.getTime();   //得到前12月的时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM"); //设置时间格式
        String defaultStartDate = sdf.format(dBefore);    //格式化前12月的时间
        String defaultEndDate = sdf.format(dNow); //格式化当前时间
        Map<String, Object> map = new HashMap<String, Object>();

        //部门应该反馈的数量
        List<DeptNum> total = deptDataService.selectJcRecieve(officeService.selectTopDeptId(userInfo.getOfficeId() + ""), startTime, endTime);

        //部门实际反馈的数量
        List<DeptNum> tota2 = deptDataService.selectJcFeedback(officeService.selectTopDeptId(userInfo.getOfficeId() + ""), startTime, endTime);

        map.put("total", total);
        map.put("tota2", tota2);
        if (startTime.equals("") || startTime == null) {
            startTime = defaultStartDate;
        } else {
            SimpleDateFormat sdfnew = new SimpleDateFormat("yyyy-MM-dd");
            startTime = sdf.format(sdfnew.parse(startTime));
        }

        if (endTime.equals("") || endTime == null) {
            endTime = defaultEndDate;
        } else {
            SimpleDateFormat sdfnew = new SimpleDateFormat("yyyy-MM-dd");
            endTime = sdf.format(sdfnew.parse(endTime));
            ;
        }
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        return new RestServiceResult(map);
    }

    /**
     * 部门参与中5个仪表盘数据
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param request
     * @return
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping("/fiveDashboard.json")
    public RestServiceResult fiveDashboard(@RequestParam(defaultValue = "", required = true, value = "startTime") String startTime,
                                           @RequestParam(defaultValue = "", required = true, value = "endTime") String endTime, HttpServletRequest request) throws ParseException {
        RestServiceResult<SysUser> user = lhjcRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null != userInfo) {

            } else {
                ExceptionLogger.error("DeptDataController#fiveDashboard", "未获取到当前用户信息！");
                return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("DeptDataController#fiveDashboard", "未获取到当前用户信息！");
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
        }

        Map<String, Object> map = new HashMap<String, Object>();

        String deptId = officeService.selectTopDeptId(userInfo.getOfficeId() + "");

        //本部门参与总量
        int total1 = deptDataService.selectJcRecieveTotal(deptId, startTime, endTime);

        //本部门响应事件数量
        int total2 = deptDataService.selectJcFeedbackTotal(deptId, startTime, endTime);

        //参与本部门发起的联合奖惩的部门数
        int total3 = deptDataService.selectOthersFeedbackTotal(deptId, startTime, endTime);

        //本部门累计反馈次数
        int total4 = deptDataService.selectDeptLj(deptId, startTime, endTime);

        //涉及联合奖惩规则数量
        int total5 = deptDataService.selectOtherSjGz(deptId, startTime, endTime);

        map.put("total1", total1);
        map.put("total2", total2);
        map.put("total3", total3);
        map.put("total4", total4);
        map.put("total5", total5);

        return new RestServiceResult(map);
    }

    /**
     * 部门参与列表数据
     *
     * @param page      分页条件
     * @param startTime 起始时间
     * @param endTime   结束时间
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/phList.json")
    public RestServiceResult getPhList(Page page,
                                       @RequestParam(value = "startTime", defaultValue = "", required = true) String startTime,
                                       @RequestParam(value = "endTime", defaultValue = "", required = true) String endTime, HttpServletRequest request) {
        RestServiceResult<SysUser> user = lhjcRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null != userInfo) {

            } else {
                ExceptionLogger.error("DeptDataController#getPhList", "未获取到当前用户信息！");
                return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
            }
        } else {
            ExceptionLogger.error("DeptDataController#getPhList", "未获取到当前用户信息！");
            return new RestServiceResult(RestServiceResult.CODE_UNKNOW, "未获取到当前用户信息！");
        }

        List<DeptData> deptData = deptDataService.getPhListForPage(officeService.selectTopDeptId(userInfo.getOfficeId() + ""), startTime, endTime, page);
        List<Map<String, Object>> lhbms = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < deptData.size(); i++) {
            Set<String> set = new HashSet<String>();
            int gzid = deptData.get(i).getGzId();
            lhbms = deptDataService.selectForLhbm(gzid);
            String lhbm = "";
            for (Map<String, Object> map : lhbms) {
                set.add((String) map.get("deptName"));
            }
            for (String obj : set) {
                lhbm += obj + ",";
            }
            deptData.get(i).setLhbm(lhbm.substring(0, lhbm.length() - 1));
        }

        return new RestServiceResult(page.getTotalCount(), deptData);
    }


}
